const httpStatus = require('http-status');
const catchAsync = require('../utils/catchAsync');
const { adminService, adminAuthService } = require('../services');

/**
 * 管理员登录
 */
const loginAdmin = catchAsync(async (req, res) => {
  const { username, password } = req.body;
  const admin = await adminAuthService.loginAdmin(username, password);
  const tokens = await adminAuthService.generateAdminToken(admin);
  
  // 添加调试信息，帮助排查问题
  console.log('生成的管理员令牌信息:', {
    adminId: admin.id,
    role: admin.role,
    permissions: admin.permissions,
    tokenExpires: tokens.access.expires
  });
  
  res.send({
    error: 0,
    body: {
      adminId: admin.id,
      token: tokens.access.token,
      name: admin.name,
      role: admin.role,
      permissions: admin.permissions
    },
    message: '登录成功'
  });
});

/**
 * 获取管理员信息
 */
const getAdminInfo = catchAsync(async (req, res) => {
  const admin = await adminService.getAdminById(req.params.adminId);
  if (!admin) {
    return res.status(httpStatus.NOT_FOUND).send({
      error: 1,
      body: null,
      message: '管理员不存在'
    });
  }
  
  res.send({
    error: 0,
    body: admin,
    message: '获取成功'
  });
});

module.exports = {
  loginAdmin,
  getAdminInfo,
}; 